package com.tinem.platform.web.file.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.tinem.platform.web.file.vo.FetchFrameVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className LinkController
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-13 19:53
 */
@Slf4j
@Controller
@RequestMapping("/video")
public class VideoController {
    @PostMapping("/fetchFrameFile.api")
    @ResponseBody
    @ApiOperation(value = "获取视频的帧并保存为图片", httpMethod = "POST", notes = "暂无")
    @Transactional(rollbackOn = Exception.class)
    public Object fetchFrameFile(@RequestParam("file") MultipartFile file
            , @RequestParam(value = "grabFrame",defaultValue = "5",required = false) String grabFrame
            , @RequestParam(value = "videoFormatName",defaultValue = "mp4") String videoFormatName
            , @RequestParam(value = "outFormatName",defaultValue = "jpeg") String outFormatName
            , HttpServletRequest request) throws IOException {
        log.info("file name:{}",file.getName());
        FetchFrameVO req = new FetchFrameVO();
        req.setFileBase64(Base64.encode(file.getBytes()));
        req.setGrabFrame(Integer.parseInt(grabFrame));
        req.setVideoFormatName(videoFormatName);
        req.setOutFormatName(outFormatName);
        return fetchFrame(req);
    }

    @PostMapping("/fetchFrame.api")
    @ResponseBody
    @ApiOperation(value = "获取视频的帧并保存为图片", httpMethod = "POST", notes = "暂无")
    @Transactional(rollbackOn = Exception.class)
    public Object fetchFrame(@Validated @RequestBody FetchFrameVO req, HttpServletRequest request){
        return fetchFrame(req);
    }
    private FetchFrameVO fetchFrame(FetchFrameVO req){
        String uuid = UUID.randomUUID().toString();
        String tmpDir = System.getProperty("java.io.tmpdir");
        File videoFile = new File(new File(tmpDir,"platform-cloud-web-file"),uuid+"."+req.getVideoFormatName());
        File imgFile = new File(new File(tmpDir,"platform-cloud-web-file"),uuid+"."+req.getOutFormatName());
        FileUtil.writeBytes(Base64.decode(req.getFileBase64()),videoFile);
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
            ff.start();
            int lenght = ff.getLengthInFrames();
            Frame f = null;
            int i = 0;
            while (i < lenght) {
                // 过滤前5帧，避免出现全黑的图片，依自己情况而定
                f = ff.grabFrame();
                if ((i > req.getGrabFrame()) && (f.image != null)) {
                    break;
                }
                i++;
            }
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bi = converter.getBufferedImage(f);
            try(ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream()){
                ImageIO.write(bi, req.getOutFormatName(),imageOutputStream);
                req.setFileBase64(Base64.encode(imageOutputStream.toByteArray()));
            }
            ff.stop();
        } catch (IOException e) {
            log.error("error",e);
        } finally {
            FileUtil.del(videoFile);
            FileUtil.del(imgFile);
        }
        return req;
    }
}
